package com.woniuxy.controller;

import com.woniuxy.pojo.dto.RolePermissionNode;
import com.woniuxy.pojo.dto.RolePermissionUpdateDTO;
import com.woniuxy.service.SysRolePermissionService;
import com.woniuxy.interfaces.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/rolePermission")
public class SysRolePermissionController {
    @Autowired
    SysRolePermissionService sysRolePermissionService;

    @Log
    @PostMapping("/getPermissionTreeByRole/{roleId}")
    public ResponseEntity<?> getPermissionTreeByRole(@PathVariable Integer roleId,
                                                     @RequestHeader("X-Button-Title") String buttonTitle,
                                                     @RequestHeader("X-User-Id") String userId){

        // 解码传入的请求头值
        buttonTitle = URLDecoder.decode(buttonTitle, StandardCharsets.UTF_8);
        userId = URLDecoder.decode(userId, StandardCharsets.UTF_8);  // 解码 userId

        List<RolePermissionNode> nodeList = sysRolePermissionService.getPermissionTreeByRole(roleId);
        System.out.println("buttonTitle = " + buttonTitle);
        System.out.println("userId = " + userId);
        return ResponseEntity.ok(nodeList);
    }

    @PostMapping("/updateRolePermissions")
    public ResponseEntity<?> updateRolePermissions(@RequestBody RolePermissionUpdateDTO dto){
        Integer roleId = dto.getRoleId();
        List<Integer> permissionIds = dto.getPermissionIds();

        Boolean success = sysRolePermissionService.updateRolePermissions(roleId,permissionIds);

        return ResponseEntity.ok(success);

    }
}
